var pageCount = 50;
var currentPage;

var commentsLoadedIds = [];
var commentsSelectedIds = [];

$(document).ready(function() {
	currentPage = 1;

    $('#commentsLoadingDiv').modal({
    	backdrop : false,
    	keyboard : false,
    	show : false
    });

    $('#commentsDeletingDiv').modal({
    	backdrop : false,
    	keyboard : false,
    	show : false
    });
	
	getComments();

	$(window).scrollTop(0);
});

function getComments() {
	$.ajax({
		async: true, 
		type: 'GET', 
		dataType: 'json', 
		url: 'action.php', 
		data: {'action' : 'queryComments', 'page' : currentPage, 'count' : pageCount}, 
		beforeSend: function() {
			$('#commentsLoadingDiv').modal('show');
		},
		success: function(data, textStatus) {
			$('#commentsLoadingDiv').modal('hide');
			
			var totalNumber = data['totalNumber'];
			var comments = data['comments'];

			var totalPage = Math.ceil(totalNumber / pageCount);
			
			if (currentPage > totalPage) {
				if (totalPage > 0) {
					currentPage = totalPage;

					getComments();
				}
			} else {
				$('#commentsCheckbox').prop('checked', false);

				$('#commentsDeleteButton').attr('class', 'btn disabled').attr('disabled', 'disabled');
				
				showComments(comments);

				showPaginations(totalPage);
			}
		}
	});
}

function getCommentCheckboxId(commentId) {
	return commentId + '_checkbox';
}

function getCommentDivId(commentId) {
	return commentId + '_div';
}

function addCommentIdToArray(commentsIds, commentId) {
	commentsIds.push(commentId);
}

function removeCommentIdFromArray(commentsIds, commentId) {
	var index = -1;
	
	for (var i = 0; i < commentsIds.length; i++) {
		if (commentId == commentsIds[i]) {
			index = i;
			break;
		}
	}

	if (index != -1) {
		commentsIds.splice(index, 1);
	}
}

function getArrayFromStr(data) {
	var array = [];
	
	var strArray = data.split(',');

	for (var i = 0; i < strArray.length; i++) {
		var str = strArray[i];
		
		if (str != '') {
			array.push(str);
		}
	}

	return array;
}

function showComments(comments) {
	$('#commentsDiv').html('');
	
	commentsLoadedIds = [];
	commentsSelectedIds = [];
	
	for (var i = 0; i < comments.length; i++) {
		var comment = comments[i];

		var replyStatus = comment['replyStatus'];
		
		var id = comment['id'];
		var text = comment['text'];
		
		var statusId = comment['statusId'];
		var statusUserId = comment['statusUserId'];
		
		var commentedText = comment['commentedText'];
		
		var commentedUserId = comment['commentedUserId'];
		var commentedUserName = comment['commentedUserName'];
		var commentedUserProfileImageUrl = comment['commentedUserProfileImageUrl'];
		
		var commentCheckboxId = getCommentCheckboxId(id);
		var commentDivId = getCommentDivId(id);

		var textHtml;
		
		if (replyStatus) {
			textHtml = text;
		} else {
			var matches = text.match('(.+)@(.+):(.+)');
			var atName = matches[2];
			
			var commentedUserHtml = 
				'<a href=\'http://weibo.com/n/' + atName + '\' target=\'_blank\' >' + 
					'@' + atName + 
				'</a>';
			
			textHtml = text.replace('@' + atName, commentedUserHtml);
		}
		
		var commentHtml = 
			'<div id=\'' + commentDivId + '\' class=\'row\' style=\'padding-top: 10px; border-bottom: 1px solid #DDDDDD;\'>'  + 
				'<div class=\'span1\'>' + 
					'<p style=\'text-align: center;\'>' + 
						'<input id=\'' + commentCheckboxId + '\' type=\'checkbox\' onclick=\'clickCommentCheckbox(' + id + ')\'/>' + 
					'</p>' + 
				'</div>' + 
				'<div class=\'span1\'>' + 
					'<p style=\'text-align: center;\'>' + 
						'<a href=\'http://weibo.com/u/' + commentedUserId + '\' title=\'' + commentedUserName + '\' target=\'_blank\' >' + 
							'<img src=\'' + commentedUserProfileImageUrl + '\' />' + 
						'</a>' + 
					'</p>' + 
				'</div>' + 
				'<div class=\'span8\'>' + 
					'<p>' + 
						textHtml + 
					'</p>' + 
					'<p>' + 
						'<span style=\'color: gray\'>' + (replyStatus ? '评论' : '回复') + '</span>' + 
						'<a href=\'http://weibo.com/u/' + commentedUserId + '\' target=\'_blank\' >' + 
							commentedUserName + 
						'</a>' + 
						'<span style=\'color: gray\'>' + '的' + (replyStatus ? '微博' : '评论') + '：' + '</span>' + 
						'<a href=\'http://api.t.sina.com.cn/' + statusUserId + '/statuses/' + statusId + '\' target=\'_blank\' >' + 
							'“' + commentedText + '”' + 
						'</a>' + 
					'</p>' + 
				'</div>' + 
				'<div class=\'span2\'>' + 
					'<p style=\'text-align: center; \'>' + 
						'<button class=\'btn btn-primary\' onclick=\'clickCommentDeleteButton(' + id + ')\'>删除</button>' + 
					'</p>' + 
				'</div>' + 
			'</div>'

		$('#commentsDiv').append(commentHtml);

		addCommentIdToArray(commentsLoadedIds, id);
	}
}

function checkComment(commentId) {
	var commentDivId = getCommentDivId(commentId);
	
	$('#' + commentDivId).css('background', '#D9EDF7');

	addCommentIdToArray(commentsSelectedIds, commentId);

	$('#commentsDeleteButton').attr('class', 'btn btn-primary').removeAttr('disabled');

	if (commentsSelectedIds.length == commentsLoadedIds.length) {
		$('#commentsCheckbox').prop('checked', true);
	}
}

function uncheckComment(commentId) {
	var commentDivId = getCommentDivId(commentId);
	
	$('#' + commentDivId).css('background', '#FFFFFF');

	removeCommentIdFromArray(commentsSelectedIds, commentId);

	if (commentsSelectedIds.length == 0) {
		$('#commentsDeleteButton').attr('class', 'btn disabled').attr('disabled', 'disabled');
	}

	if (commentsSelectedIds.length != commentsLoadedIds.length) {
		$('#commentsCheckbox').prop('checked', false);
	}
}

function clickCommentCheckbox(commentId) {
	var commentCheckboxId = getCommentCheckboxId(commentId);

	var commentCheckboxChecked = $('#' + commentCheckboxId).prop('checked');
	
	if (commentCheckboxChecked) {
		checkComment(commentId);
	} else {
		uncheckComment(commentId);
	}
}

function clickCommentsCheckbox(commentsCheckboxChecked) {
	if (commentsCheckboxChecked) {
		for (var i = 0; i < commentsLoadedIds.length; i++) {
			var commentId = commentsLoadedIds[i];

			var commentCheckboxId = getCommentCheckboxId(commentId);

			$('#' + commentCheckboxId).prop('checked', true);
			
			checkComment(commentId);
		}
	} else {
		for (var i = 0; i < commentsLoadedIds.length; i++) {
			var commentId = commentsLoadedIds[i];

			var commentCheckboxId = getCommentCheckboxId(commentId);

			$('#' + commentCheckboxId).prop('checked', false);
			
			uncheckComment(commentId);
		}
	}
}

function deleteComment(commentsIds) {
	$.ajax({
		async: true, 
		type: 'POST', 
		dataType: 'text', 
		url: 'action.php', 
		data: {'action' : 'deleteComments', 'commentsIds' : commentsIds}, 
		beforeSend: function() {
			$('#commentsDeletingDiv').modal('show');
		},
		success: function(data, textStatus) {
			$('#commentsDeletingDiv').modal('hide');
			
			var deletedCommentsIds = getArrayFromStr(data);

			for (var i = 0; i < deletedCommentsIds.length; i++) {
				var commentId = deletedCommentsIds[i];
				
				uncheckComment(commentId);
				
				var commentDivId = getCommentDivId(commentId);

				$('#' + commentDivId).remove();

				removeCommentIdFromArray(commentsLoadedIds, commentId);

				if (commentsLoadedIds.length == 0) {
					$('#paginationDiv ul').html('');
					
					getComments();
				}
			}
		}
	});
}

function clickCommentDeleteButton(commentId) {
	deleteComment(commentId);
}

function clickCommentsDeleteButton() {
	deleteComment(commentsSelectedIds.join(','));
}

function clickPagination(page) {
	currentPage = page;

	getComments();
}

function showPaginations(totalPage) {
	$('#paginationDiv ul').html('');

	if (currentPage == 1) {
		$('#paginationDiv ul').append('<li href=\'#\' class=\'disabled\'><a>&lt;&lt;</a></li>');
	} else {
		$('#paginationDiv ul').append('<li><a href=\'#\' onclick=\'clickPagination(' + (currentPage - 1) + ')\'>&lt;&lt;</a></li>');
	}

	for (var i = 1; i <= totalPage; i++) {
		if (currentPage == i) {
			$('#paginationDiv ul').append('<li href=\'#\' class=\'active\'><a>' + i + '</a></li>');
		} else {
			$('#paginationDiv ul').append('<li><a href=\'#\' onclick=\'clickPagination(' + i + ')\'>' + i + '</a></li>');
		}
	}

	if (currentPage == totalPage) {
		$('#paginationDiv ul').append('<li href=\'#\' class=\'disabled\'><a>&gt;&gt;</a></li>');
	} else {
		$('#paginationDiv ul').append('<li><a href=\'#\' onclick=\'clickPagination(' + (currentPage + 1) + ')\'>&gt;&gt;</a></li>');
	}
}